<template>
  <view class="pageView">
    <view class="scrollview">
      <scroll-view
        scroll-y
        scroll-x
        show-scrollbar
        scroll-with-animation
        :scroll-top="scrollTop"
        class="scroll-content"
      >
        <view class="chat-content">
          <block v-if="messageList.length">
            <block v-for="(item, index) in messageList" :key="index">
              <view :class="item.role" :id="'message-' + index">
                <view
                  class="chatbox"
                  :class="item.role == 'user' ? ' chatbox-right' : 'chatbox-left'"
                >
                  <block v-if="item.content">
                    <view class="chat_content">
                      <block v-if="item.role == 'user'">
                        <text space="nbsp" selectable user-select>{{
                          item.content
                        }}</text>
                      </block>
                      <block v-else>
                        <!-- 替换为普通text组件，先验证数据是否能显示 -->
                        <text>{{ item.content }}</text>
                        <!-- 若text能显示，再换回ul-markdown，确保格式正确 -->
                        <!-- <ul-markdown :source="item.content" /> -->
                      </block>
                      <block v-if="item.role == 'assistant'">
                        <view class="chat_btn" v-if="retryState && index == messageList.length - 1">
                          <view class="icon" @click="bindretry">
                            <text style="font-size: 24rpx; color: #8c8c8c;">⟳</text>
                          </view>
                        </view>
                      </block>
                    </view>
                  </block>
                  <block v-else>
                    <view class="loading"><text style="font-size: 36rpx; color: #0d0d0d; animation: spin 1s linear infinite;">⏳</text></view>
                  </block>
                </view>
              </view>
            </block>
          </block>
          <block v-else>
            <view class="none">{{ text }}</view>
          </block>
        </view>
      </scroll-view>
    </view>
    <!-- 底部输入框 -->
    <view class="bottom">
      <view class="bottom_border" :style="{ marginBottom: `${keyboardHeight}px` }">
        <view class="bottom_textarea">
          <textarea
            cursor-spacing="70"
            @keyboardheightchange="keyboardheightchange"
            auto-height
            v-model="inputText"
            :adjust-position="false"
            maxlength="-1"
            placeholder="询问任何问题"
          ></textarea>
        </view>
        <view class="bottom_button">
          <view class="Upload">
            <button disabled class="uv-reset-button upload_btn">
              <text style="font-size: 32rpx; color: #8c8c8c;">+</text>
            </button>
            <button :disabled="!messageList.length" class="trash-btn" @click="bindtrash">
              <text class="trash-icon">🗑️</text>
            </button>
          </view>
          <view class="sending">
            <button
              @click="bindSendMessage"
              :disabled="!inputText"
              v-if="!stopState"
              class="send-btn"
              :class="{ 'active': inputText }"
            >
              <text class="send-icon">→</text>
            </button>
            <button @click="bindSendStop" v-if="stopState" class="stop-btn">
              <text class="stop-icon">❚❚</text>
            </button>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
// 注释掉不存在的导入，需要根据实际路径调整
// import { fetchDeepSeekStream } from '@/utils/deepseek.js';
import { ref, onMounted, watch, nextTick } from 'vue';
import { onLoad } from '@dcloudio/uni-app';

let stopStream = null;

const inputText = ref('');
const scrollTop = ref(0);
const messageList = ref([]);
const keyboardHeight = ref(0);
const inputMessage = ref('');
// 是否需要中断
const stopState = ref(false);

//重试
const retryState = ref(false);
const text = '有什么可以帮忙的?';
// 页面生命周期函数 onLoad
onLoad(() => {
  // console.log('页面生命周期函数,onLoad');
});
onMounted(() => {
  // 组件加载后滚动到底部
  const storedMessages = uni.getStorageSync('messageList');
  if (storedMessages) {
    messageList.value = storedMessages;
    setTimeout(() => {
      scrollIntoView();
    }, 1000);
  }
});
watch(
  messageList,
  () => {
    nextTick(() => {
      scrollIntoView();
    });
  },
  { deep: true, immediate: true } // 深度监听 + 组件加载时立即执行
); // 立即触发，确保 onMounted 时也能执行
// 发送消息
const bindSendMessage = async () => {
  if (!inputText.value.trim()) return;
  // 记录用户消息
  messageList.value.push({
    role: 'user',
    content: inputText.value
  });
  inputText.value = '';
  // 添加占位 AI 消息
  messageList.value.push({
    role: 'assistant',
    content: ''
  });
  nextTick(() => {
    scrollIntoView();
  });
  // 获取 AI 消息索引
  const lastIndex = messageList.value.length - 1;
  stopState.value = true;
  retryState.value = false;
  // console.log('开始调用fetchDeepSeek，lastIndex：', lastIndex);
  fetchDeepSeek(lastIndex);
};
const bindtrash = () => {
  uni.showModal({
    title: '提示',
    content: '确定要清空所有聊天记录吗？',
    success: (res) => {
      if (res.confirm) {
        messageList.value = [];
        uni.clearStorageSync();
      }
    }
  });
};
const scrollIntoView = () => {
  nextTick(() => {
    if (messageList.value.length > 0) {
      const lastMessageId = `message-${messageList.value.length - 1}`;
      uni.createSelectorQuery()
        .select(`#${lastMessageId}`)
        .boundingClientRect((rect) => {
          if (rect) {
            uni.pageScrollTo({
              scrollTop: rect.top,
              duration: 300
            });
          }
        })
        .exec();
    }
  });
};
const fetchDeepSeek = (lastIndex) => {
  // 模拟API调用，因为fetchDeepSeekStream不存在
  stopState.value = true;
  retryState.value = false;
  
  // 模拟异步响应
  setTimeout(() => {
    // 模拟AI回复内容
    const mockResponses = [
      '您好，我是客服助手，有什么可以帮助您的？',
      '感谢您的咨询，我会尽力为您解答问题。',
      '关于您的问题，我需要了解更多信息才能给您准确的答复。',
      '这是一个模拟回复，实际应用中需要调用真实的API接口。'
    ];
    
    // 随机选择一个回复
    const randomResponse = mockResponses[Math.floor(Math.random() * mockResponses.length)];
    
    // 模拟打字效果
    let currentLength = 0;
    const typeInterval = setInterval(() => {
      if (currentLength < randomResponse.length) {
        currentLength++;
        messageList.value[lastIndex].content = randomResponse.substring(0, currentLength);
      } else {
        clearInterval(typeInterval);
        stopState.value = false;
        uni.setStorageSync('messageList', messageList.value);
      }
    }, 50);
    
    // 保存stopStream函数用于中断
    stopStream = () => {
      clearInterval(typeInterval);
      messageList.value[lastIndex].content = randomResponse.substring(0, currentLength);
      console.log('请求已手动中断');
    };
  }, 500);
};
// 重试
const bindretry = () => {
  if (messageList.value.length === 0) return; // 确保有数据可以重试
  const lastIndex = messageList.value.length - 1; // 获取删除前的索引
  retryState.value = false;
  messageList.value[lastIndex].content = '';
  stopState.value = true;
  fetchDeepSeek(lastIndex); // 重新请求
};
// 终止请求
const bindSendStop = () => {
  if (stopStream) {
    stopStream(); // 终止请求
  }
  stopState.value = false;
  retryState.value = true;
};
// 计算键盘高度变化
const keyboardheightchange = (e) => {
  keyboardHeight.value = e.detail.height;
};
</script>

<style lang="scss">
.none {
  font-weight: 500;
  font-size: 30rpx;
  color: #333333;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  margin-top: 0; /* 移除额外的顶部 margin，确保垂直居中 */
}
.pageView {
  display: flex;
  flex-direction: column;
  height: 100vh; /* 让整个页面占满屏幕 */
  overflow: hidden; /* 防止页面整体滚动 */
}

.scrollview {
  flex: 1; /* 让 scroll-view 占据剩余空间 */
  overflow: hidden;
  box-sizing: border-box;
  padding-top: 20rpx; /* 顶部留出一些空间 */
}

.scroll-content {
  height: 100%;
  box-sizing: border-box;
  padding-bottom: 20rpx; /* 底部留出一些空间 */
}

.chat-message {
  background: #fff;
  padding: 20rpx;
  margin-bottom: 20rpx;
  border-radius: 10rpx;
}

.bottom {
  display: flex;
  align-items: center;
  background: #fff;
  padding: 20rpx;
  padding-top: 4rpx;
  padding-bottom: calc(constant(safe-area-inset-bottom) + 20rpx);
  padding-bottom: calc(env(safe-area-inset-bottom) + 20rpx);
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05); /* 添加阴影区分内容区 */
}
.bottom_border {
  width: 100%;
  border: 1rpx solid #f5f5f5;
  border-radius: 40rpx;
  padding: 20rpx 24rpx;
  box-shadow: 0rpx 2rpx 4rpx 0rpx #ccc;
  transition: 0.2s;
  .bottom_textarea {
    textarea {
      width: 100%;
      font-weight: 500;
      font-size: 32rpx;
      color: #222222;
      max-height: 400rpx;
    }
  }
  .bottom_button {
      height: 80rpx;
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-top: 10rpx;
      .Upload {
        display: flex;
        align-items: center;
        button {
          width: 65rpx;
          height: 65rpx;
          border-radius: 50%;
          border: 2rpx solid #e8e8e8;
          box-sizing: border-box;
          display: flex;
          justify-content: center;
          align-items: center;
          margin-right: 20rpx;
        }
        .trash-btn {
          width: 65rpx;
          height: 65rpx;
          border-radius: 50%;
          border: 2rpx solid #e8e8e8;
          background-color: #fff;
          box-sizing: border-box;
          display: flex;
          justify-content: center;
          align-items: center;
          margin-right: 20rpx;
        }
        .trash-btn:disabled {
          opacity: 0.5;
        }
        .trash-icon {
          font-size: 32rpx;
          color: #8c8c8c;
        }
      }
    .sending {
      button {
        width: 65rpx;
        height: 65rpx;
        border-radius: 50%;
        border: 2rpx solid #f7f7f7;
        box-sizing: border-box;
        display: flex;
        justify-content: center;
        align-items: center;
      }
    }
    .send-btn {
      width: 65rpx;
      height: 65rpx;
      border-radius: 50%;
      background-color: #ccc;
      border: none;
      display: flex;
      justify-content: center;
      align-items: center;
    }
    .send-btn.active {
      background-color: #0d0d0d;
    }
    .send-icon {
      font-size: 32rpx;
      color: #fff;
      font-weight: bold;
    }
    .stop-btn {
      width: 65rpx;
      height: 65rpx;
      border-radius: 50%;
      background-color: #0d0d0d;
      border: none;
      display: flex;
      justify-content: center;
      align-items: center;
    }
    .stop-icon {
      font-size: 20rpx;
      color: #fff;
      font-weight: bold;
    }
  }
}

.chat-content {
  margin: 0 30rpx;
  position: relative;
  min-height: 100%; /* 确保内容区域高度足够 */
  padding: 20rpx 0; /* 增加上下内边距 */
}

.chatbox {
  border-radius: 10rpx;
  position: relative;
  font-size: 32rpx;
  color: #333;
  word-break: break-all;
  word-wrap: break-word;
  margin-bottom: 20rpx; /* 增加消息之间的间距 */
  .chat_content {
    font-size: 28rpx;
    width: fit-content;
    .chat_btn {
      display: flex;
      align-items: center;
      margin-top: 6rpx;
      .icon {
        margin-right: 10rpx;
      }
    }
  }
}

.chatbox-left {
  background: #fff;
  display: inline-block;
  justify-content: flex-start;
  max-width: 70%;
  padding: 24rpx 28rpx; /* 增加内边距让内容更舒展 */
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05); /* 添加轻微阴影 */
}

.chatbox-right {
  background: #f5f5f5;
  max-width: 70%;
  padding: 24rpx 28rpx; /* 增加内边距让内容更舒展 */
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05); /* 添加轻微阴影 */
}

.user {
  display: flex;
  align-items: flex-start;
  padding: 10rpx 0rpx; /* 减少上下间距 */
  justify-content: flex-end;
}
.assistant {
  display: flex;
  align-items: flex-start;
  padding: 10rpx 0rpx; /* 减少上下间距 */
}
.loading {
  display: flex;
  padding: 20rpx; /* 给加载状态增加内边距 */
}

@keyframes spin {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}
</style>